package com.cw.paging3

import android.os.Bundle
import android.util.Log
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import androidx.recyclerview.widget.LinearLayoutManager
import com.cw.paging3.databinding.ActivityMainBinding
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {

    // 此处必须用val
    val viewModel: MainViewModel by viewModels()
    lateinit var mainListAdapter: MainListAdapter
    lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        // 此处一定要替换掉
        setContentView(binding.root)
        setupList()
        setupView()
    }

    private fun setupView() {
        lifecycleScope.launch {
            viewModel.getPagingData().collect {
                mainListAdapter.submitData(it)
            }
        }
    }

    private fun setupList() {
        mainListAdapter = MainListAdapter()
        binding.recyclerView.apply {
            layoutManager = LinearLayoutManager(this@MainActivity)
            adapter = mainListAdapter
        }
        mainListAdapter.addLoadStateListener {
            // 状态返回的参数 CombinedLoadStates，包含了
            //refresh，prepend，append,source,mediator 五种行为的状态
            //分别是：
            //刷新，向前加载更多，向后加载更多，数据源，调解员
            when (it.refresh) {
                is LoadState.NotLoading -> {
                }
                is LoadState.Loading -> {
                }
                is LoadState.Error -> {
                }
            }
            when(it.append) {
                is LoadState.NotLoading -> {
                    if (it.append.endOfPaginationReached) {
                        Log.e("TAG", "加载完成")
                    }
                }
            }
        }
    }

//    private fun setupViewModel() {
//        viewModel =
//            ViewModelProvider(
//                this,
//                MainViewModelFactory(APIService.getApiService())
//            )[MainViewModel::class.java]
//    }
}
